package com.utils;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;


public class PropertiesInstance {

    public static final String ROOT = "a.properties";

    private static PropertiesInstance propertiesInstance = null;

    private Properties p = null;

    public static PropertiesInstance getInstance() {
        if (propertiesInstance == null) {
            synchronized (PropertiesInstance.class) {
                if (propertiesInstance == null) {
                    propertiesInstance = new PropertiesInstance();
                }
            }
        }
        return propertiesInstance;
    }

    /**
     * 检查文件是否存在并创建
     */
    private void checkFileExitAndCreate() {
        try {
            File file = new File(ROOT);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取配置文件
     *
     * @return
     */
    private void readProperties() {
        try {
            checkFileExitAndCreate();
            File file = new File(ROOT);
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
            p = new Properties();
            p.load(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定KEY
     *
     * @param key
     * @return
     */
    public String getKey(String key) {
        if (p == null) {
            readProperties();
        }

        if (p != null) {
            return p.getProperty(key);
        }

        return null;
    }

    /**
     * 添加指定KEY
     *
     * @param key
     */
    public void putKey(String key, String content) {
        if (p == null) {
            readProperties();
        }

        if (p != null) {
            try {
                p.put(key, content);
                File file = new File(ROOT);
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
                p.setProperty(key, content);
                p.store(os, null);
                os.flush();
                os.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
